﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace Winform翻译机
{
    public partial class TranslationForm : Form
    {
        public TranslationForm()
        {
            InitializeComponent();
            rtbChinseTo.Text = Translator.Translate("双击文本框可清空内容！", "zh", "auto");
            rtbEnglishTo.Text = Translator.Translate("Double click the text box to empty the contents！", "en", "auto");
        }      

       #region 调用百度翻译api的类
        class Translator
        {
            public static string Translate(string src, string from, string to)
            {
                string text = getRequest(src, from, to);
                BaiduResult r = jsonGet(text);
                if (r != null && r.trans_result != null && r.trans_result.Length > 0)
                    return r.trans_result[0].dst;
                else
                    return "";
            }

            public static string[] Translate(string[] src, string from, string to)
            {
                StringBuilder sb = new StringBuilder();
                int size = src.Length;
                List<string> ls = new List<string>();
                int i;
                for (i = 0; i < size; i += 10)
                {
                    sb.Remove(0, sb.Length);
                    for (int j = 0; j < 10; j++)
                    {
                        if (i + j < size)
                            sb.AppendLine(src[i + j]);
                    }
                    string text = getRequest(sb.ToString(), from, to);
                    BaiduResult r = jsonGet(text);
                    if (r != null && r.trans_result != null)
                    {
                        foreach (BaiduResult.Trans_result tr in r.trans_result)
                        {
                            ls.Add(tr.dst);
                        }
                    }
                }
                return ls.ToArray();
            }

            private static string MD5(string str)
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
            }

            private static Random rnd = new Random();
            private static string appid = "20160320000016075";
            private static string secret_key = "NYNXVfXdJ2Wp9ysC0MJd";


            protected static string getRequest(string src, string from, string to)
            {
                //Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(src));
                string q = System.Web.HttpUtility.UrlEncode(src, System.Text.Encoding.UTF8);
                string salt = rnd.Next().ToString();

                string sign = MD5(appid + src + salt + secret_key);
                string address = string.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}", q, from, to, appid, salt, sign);
                
                HttpWebRequest request;
                request = (HttpWebRequest)HttpWebRequest.Create(address);
                request.Method = "GET";
                request.ProtocolVersion = HttpVersion.Version11;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Timeout = 10000;

                request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
                request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
                request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
                request.CookieContainer = new CookieContainer();

                HttpWebResponse response;
                response = (HttpWebResponse)request.GetResponse();
                Stream st;
                st = response.GetResponseStream();
                GZipStream temp = null;
                StreamReader stReader;
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                {
                    temp = new GZipStream(st, CompressionMode.Decompress, true);
                    stReader = new StreamReader(temp, Encoding.Default);
                }
                else
                {
                    stReader = new StreamReader(st, Encoding.Default);
                }

                string text;
                text = stReader.ReadToEnd();

                stReader.Close();
                if (temp != null)
                    temp.Close();
                st.Close();
                return text;
            }

            public static BaiduResult jsonGet(string jsonString)
            {
                if (jsonString.Length > 0)
                {
                    var ms = new MemoryStream(Encoding.Default.GetBytes(jsonString));
                    return (BaiduResult)new DataContractJsonSerializer(typeof(BaiduResult)).ReadObject(ms);
                }
                return null;
            }
        }

        public class BaiduResult
        {
            [DataMember(Order = 0, IsRequired = true)]
            public string from;
            [DataMember(Order = 1)]
            public string to;
            public class Trans_result
            {
                public string src;
                public string dst;
            }
            [DataMember(Order = 2)]
            public Trans_result[] trans_result;
        }
        #endregion


        private void btnAutoTranslate_Click(object sender, EventArgs e)
        {
            rtbEnglishTo.Text = "";
            string[] lines = rtbChinseTo.Text.Split('\n');
            string[] results = Translator.Translate(lines, "auto", "auto");
            foreach (string line in results)
                rtbEnglishTo.AppendText(line + "\n");
        }

        private void btnAutoTranslation_Click(object sender, EventArgs e)
        {
            rtbChinseTo.Text = "";
            string[] lines = rtbEnglishTo.Text.Split('\n');
            string[] results = Translator.Translate(lines, "auto", "auto");
            foreach (string line in results)
                rtbChinseTo.AppendText(line + "\n");
        }

        private void rtb_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            RichTextBox rtb = (RichTextBox)sender;
            rtb.Clear();
        }
         
    }
}
